/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        unordered_set<ListNode*> s;
        ListNode* cur = head;
        while (cur)
        {
            if (s.count(cur))
                return cur;
            s.insert(cur);
            cur = cur->next;
        }
        return nullptr;

    }
};

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        ListNode* slow = head;
        ListNode* last = head;
        while (last && last->next)
        {
            last = last->next->next;
            slow = slow->next;
            if (last == slow)
            {
                ListNode* cur = head;
                ListNode* prev = slow;
                while (cur && prev)
                {
                    if (prev == cur)
                        return cur;
                    prev = prev->next;
                    cur = cur->next;
                }
            }
        }
        return nullptr;

    }
};